package com.archermind.boc.ehcache;

import java.util.LinkedList;
import java.util.List;

import com.archermind.boc.Logger;
import com.archermind.boc.domain.Biz;
import com.archermind.boc.domain.IQ;
import com.archermind.boc.utility.BizHelper;
import com.archermind.boc.xml.ApplicationContextFactory;

public class OperatorQueue {
	private static Logger log = Logger.getLogger(OperatorQueue.class.getName());

	private static Object object = new Object();

	private static OperatorQueue oq = null;

	public static List<Object[]> ls = new LinkedList<Object[]>();

	private BizHelper bizHelper = (BizHelper) ApplicationContextFactory
			.getContext().getBean("BizHelper");

	private UserEhcacheImpl ue = (UserEhcacheImpl) ApplicationContextFactory
			.getContext().getBean("userEhcache");

	public static long timeOut = 30 * 1000;

	private OperatorQueue() {
		new Thread() {
			public void run() {
				while (true) {
					pullQueue();
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}.start();
	}

	public static OperatorQueue getInstance() {
		synchronized (object) {
			if (oq == null) {
				oq = new OperatorQueue();
			}
		}
		return oq;
	}

	public void addQueue(Object[] u) {
		synchronized (ls) {
			log.error("add object!" + ((IQ) u[3]).getSessionID());
			u[2] = System.currentTimeMillis();
			ls.add(u);
		}
	}

	public void removeQueue(Object[] u) {
		synchronized (ls) {
			log.error("remove object!" + ((IQ) u[3]).getSessionID());
			ls.remove(u);
		}
	}

	public void pullQueue() {
		synchronized (ls) {
			Object[] objectArray = null;
			for (int i = 0; i < ls.size(); i++) {
				objectArray = ls.get(i);
				if (isTimeOut(objectArray)) {
					removeQueue(objectArray);
					i--;
					ue.backToOperator(((UserCache) objectArray[0]).getUserid(),
							((Biz) objectArray[1]));
					continue;
				} else {
					UserCache authorUC = ue.suitableUser(
							((UserCache) objectArray[0]).getUserid(),
							((Biz) objectArray[1]));
					if (authorUC == null) {
						continue;
					} else {
						bizHelper.grant(authorUC, (IQ) objectArray[3],
								((Biz) objectArray[1]));
						removeQueue(objectArray);
						i--;
					}
				}

			}
		}
	}

	public boolean isTimeOut(Object[] uc) {
		if ((System.currentTimeMillis() - (Long) uc[2]) > timeOut) {
			return true;
		} else {
			return false;
		}
	}

	public static void main(String[] args) throws InterruptedException {
		OperatorQueue oq = new OperatorQueue();
		Thread.sleep(1000);
		Object[] o = new Object[4];
		oq.addQueue(o);
		Thread.sleep(4000);
		oq.addQueue(o);
		System.out.println("after oq");
	}
}
